package com.yiwei.zxp.activity;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.yiwei.zxp.R;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.SmsSendBean;
import com.yiwei.zxp.api.bean.UserSetPayBean;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.constant.UserInfoGlobal;
import com.yiwei.zxp.util.MD5;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.view.V19FrameLayout;
import com.yiwei.zxp.view.keyboard.Keyboard;
import com.yiwei.zxp.view.keyboard.PayEditText;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class AccountSecurityActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.pay_edit_text)
    PayEditText payEditText;
    @BindView(R.id.keyboard)
    Keyboard keyboard;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.btn_send_code)
    TextView btnSendCode;
    private boolean isSendCode = true;
    private String payPass;
    private String phone;
    private static final int TIME = 60 * 1000;  //验证码倒计时时间
    private CountDownTimer timer = new CountDownTimer(TIME, 1000) {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onTick(long millisUntilFinished) {
            btnSendCode.setText("重新获取" + (millisUntilFinished / 1000) + "s");
            if (isSendCode) {
                isSendCode = false;
                btnSendCode.setEnabled(false);
                btnSendCode.setBackgroundResource(R.drawable.btn_send_code_uncheck);
                btnSendCode.setTextColor(0xFFFFFFFF);
            }

        }

        @Override
        public void onFinish() {
            isSendCode = true;
            resetBtn();
        }
    };

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void resetBtn() {
        if (timer != null) timer.cancel();
        btnSendCode.setEnabled(true);
        btnSendCode.setText("获取验证码");
        btnSendCode.setTextColor(0xFFFF0030);
        btnSendCode.setBackgroundResource(R.drawable.btn_send_code_check);
    }

    private Unbinder unbiner;
    private static final String[] KEY = new String[]{
            "1", "2", "3",
            "4", "5", "6",
            "7", "8", "9",
            "<<", "0", "完成"
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_security);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtTitle.setText("账户安全");
        keyboard.setKeyboardKeys(KEY);
//键盘键的点击事件
        keyboard.setOnClickKeyboardListener(new Keyboard.OnClickKeyboardListener() {
            @Override
            public void onKeyClick(int position, String value) {
                if (position < 11 && position != 9) {
                    payEditText.add(value);
                } else if (position == 9) {
                    payEditText.remove();
                } else if (position == 11) {
                    //当点击d键盘上的完成时候，也可以通过payEditText.getText()获取密码，此时不应该注册OnInputFinishedListener接口
//                    ToastUtil.makeText(getApplicationContext(), "您的密码是：" + payEditText.getText());
                    if (payEditText.getText().length() < 6) {
                        ToastUtil.makeText(getApplicationContext(), "交易密码要6位");
                        return;
                    }
                    btnSubmit.setSelected(true);
                    payPass = payEditText.getText();
                    keyboard.setVisibility(View.GONE);
                }
            }
        });

//当密码输入完成时的回调
        payEditText.setOnInputFinishedListener(new PayEditText.OnInputFinishedListener() {
            @Override
            public void onInputFinished(String password) {
//                ToastUtil.makeText(getApplicationContext(), "您的密码是：" + password);
                btnSubmit.setSelected(true);
                payPass = payEditText.getText();
                keyboard.setVisibility(View.GONE);
            }

            @Override
            public void onClick() {
                keyboard.setVisibility(View.VISIBLE);
            }
        });
        editPhone.setText(UserInfoGlobal.getPhone());
    }

    public void getSmsSend(String phone) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        SmsSendBean bean = new SmsSendBean();
        bean.phone = phone;
        Api.api_service.getForgetSend(bean).compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "验证码已发送，请注意查收");
                    timer.start();
                });
    }

    public void getPassSet(String phone, String password, String verify_code) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        UserSetPayBean bean = new UserSetPayBean();
        bean.phone = phone;
        bean.password = MD5.getMD5str(password);
        bean.verify_code = verify_code;
        Api.api_service.getPassPay(bean).compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    UserInfoGlobal.getSetPayPass();
                    ToastUtil.makeText(this, "设置成功");
                    finish();
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        unbiner.unbind();
        unbiner = null;
    }


    @OnClick({R.id.btn_back, R.id.btn_send_code, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_send_code:
                if (TextUtils.isEmpty(UI.toString(editPhone))) {
                    ToastUtil.makeText(this, "手机号不能为空");
                    return;
                }
                getSmsSend(UI.toString(editPhone));
                break;
            case R.id.btn_submit:
                if (TextUtils.isEmpty(UI.toString(editPhone))) {
                    ToastUtil.makeText(this, "手机号不能为空");
                    return;
                }

                if (TextUtils.isEmpty(UI.toString(editCode))) {
                    ToastUtil.makeText(this, "验证码不能为空");
                    return;
                }

                if (TextUtils.isEmpty(payPass)) {
                    ToastUtil.makeText(this, "交易密码不能为空");
                    return;
                }
                getPassSet(UI.toString(editPhone), payPass, UI.toString(editCode));
                break;
        }
    }
}
